package com.xiaomaoguai.fcp.pre.kepler.redis.listener;

import com.xiaomaoguai.fcp.pre.kepler.redis.configuration.MyRedisAutoConfiguration;
import com.xiaomaoguai.fcp.pre.kepler.redis.listener.anno.RedisListener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import javax.annotation.Resource;

/**
 * @author WeiHui-Z
 * @version v1.0.0
 * @date 2019/6/4 15:20
 * @since JDK 1.8
 */
@Configuration
@AutoConfigureAfter(MyRedisAutoConfiguration.class)
public class RedisListenerAutoConfiguration implements BeanPostProcessor {

	@Resource
	private GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer;

	@Resource
	private RedisMessageListenerContainer redisMessageListenerContainer;

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		final RedisListener redisListener = bean.getClass().getAnnotation(RedisListener.class);
		if (redisListener != null) {
			MessageListenerAdapter messageListener = new MessageListenerAdapter();
			messageListener.setDelegate(bean);
			messageListener.setSerializer(genericJackson2JsonRedisSerializer);
			messageListener.afterPropertiesSet();
			String value = redisListener.value();
			redisMessageListenerContainer.addMessageListener(messageListener, new ChannelTopic(value));
		}
		return bean;
	}

}
